<script>
export default {
  created() {
    this.goods_list()
  },
  data() {
    return {
      tableData: [],
      input: '', // 输入框
      flower_infor: {}, // 弹出框数据
      page_total: 0, // 分页总条数
      do_title: '修改商品',
      centerDialogVisible: false, // 控制弹出框
      imgUrl: [], // 图片地址
      create_url: [], // 上传时的图片地址
      dialogVisible: false, // 对话框是否可见
      disabled: false, // 是否禁用删除
      flag: 1, //控制是修改/新增
      flower_type: ['玫瑰花', '永生花', '蛋糕', '巧克力'], // 花的类型
      flower_give: ['恋人', '朋友', '长辈', '生日蛋糕'], // 送花的对象
      flower_special: ['热销', '特价', '新品', '品味之选'], // 专区
      count: 0,  //计算图片数量
    }
  },
  methods: {
    // 初始化时的页面
    async goods_list() {
      const { data: res } = await this.$http.get(
        '/flower-goods/list?userId=' + localStorage.getItem('userId')
      )
      this.is_for(res)
    },
    clear_array() {
      this.tableData.splice(0, this.tableData.length) // 清空数组方法
    },
    // for循环
    is_for(res) {
      this.clear_array() // 清空数组
      this.page_total = res.data.length
      for (var i = 0; i <= res.data.length - 1; i++) {
        this.tableData.push(res.data[i])
      }
    },
    // 分页
    async changePageCurrent(page) {
      const { data: res } = await this.$http.get(
        '/flower-goods/list?current_page=' +
          page +
          'userId=' +
          localStorage.getItem('userId')
      )
      this.is_for(res)
    },
    // 搜索
    async search_goods() {
      const { data: res } = await this.$http.get(
        '/flower-goods/search?goods_name=' + this.input
      )
      this.$message.success(res.msg)
      this.is_for(res)
    },
    // 删除
    async delete_goods(goodsId) {
      const { data: res } = await this.$http.delete(
        '/flower-goods/delete/' + goodsId
      )
      if (res.code) {
        this.$message.success(res.data)
        this.goods_list()
      } else {
        this.$message.error(res.msg)
      }
    },
    // 修改商品状态
    async slot_btn(data, row) {
      row.goodsStatus = data === 1 ? 2 : 1
      const { data: res } = await this.$http.put(
        '/flower-goods/updateStatus/' + row.goodsId + '/' + row.goodsStatus
      )
      if (res.code === 1) {
        this.$message.success(res.data)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 调用修改商品，查询商品信息
    async btn_update(row) {
      this.clear_flower()
      this.flag = 1 // 修改状态为修改时的状态
      this.centerDialogVisible = true
      this.do_title = '修改商品'
      const { data: res } = await this.$http.get(
        '/flower-goods/update_list/' + row.goodsId
      )
      this.flower_infor = res.data
      if(this.flower_infor.goodsImg != null){
        this.imgUrl = this.flower_infor.goodsImg.split(",")
        this.count = this.imgUrl.length // 获取长度，不能让图片比4张多
      }
    },
    // 清除数据
    clear_flower() {
      this.flower_infor = {}
      this.imgUrl = []
      this.count = 0
      this.create_url = []
    },

    // 新增商品
    btn_insert() {
      this.count = 0
      this.clear_flower()// 清空数据
      this.flag = 2 // 修改状态为新增时的状态
      this.do_title = '添加商品'
      this.centerDialogVisible = true // 控制弹框显示
    },
    // 删除图片
    handleRemove(file) {
      console.log(file)
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      console.log(file);
    },
    // 修改、新增
    async btn_definite() {
      this.centerDialogVisible = false
      for(var j = 0; j < this.create_url.length; j++){
          this.imgUrl.push(this.create_url[j])
      }
      this.flower_infor.goodsImg = "" // 清空字符串
      // 图片拼接
      for (var i = 0; i <= this.imgUrl.length - 1; i++) {
        this.flower_infor.goodsImg += this.imgUrl[i]
        if (i === this.imgUrl.length - 1) {
          break
        }
        this.flower_infor.goodsImg += ','
      } // 把图片数据存入要发给后端的实体中
      if (this.flag === 1) {
        // 修改
        const { data: res } = await this.$http.put(
          '/flower-goods/update',
          this.flower_infor
        )
        this.$message.success(res.data)
      } else {
        // 新增
        // this.flower_infor.goodsImg = this.flower_infor.goodsImg.substr(9) // 新增时前面会多一个未定义的表示，需要截取掉
        this.$set(this.flower_infor, 'userId', localStorage.getItem('userId')) // 新增一个字段  我们需要把用户的id也放进去
        const { data: res } = await this.$http.post(
          '/flower-goods/insert',
          this.flower_infor
        )
        if (res.code === 1) {
          this.$message.success(res.data)
        } else {
          this.$message.error(res.msg)
        }
      }
      this.goods_list();
    },
    // 上传成功时调用
    onSuccess(res, file) {
      if(this.count != 4){
        if (res.code === 1) {
        this.create_url.push(file.response.data) // push进数组
      } else {
        this.$message.error('上传失败')
      }
      }
    },
    // 用于判断图片格式和图片大小
    beforeAvatarUpload(file) {
      const isJPGANDPNG = file.type === 'image/jpeg' || 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPGANDPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPGANDPNG && isLt5M
    },
    qu_xiao(){
      this.centerDialogVisible = false
      this.goods_list();
    },
    // 文件改变时会调用这个方法
    onChange(file) {
      if(this.count == 4){
        this.$message.error("图片已经上限")
      }else if(file.status == "success"){
        this.count++
      }
    }
  },
}
</script>
<template>
  <div class="app">
    <div class="header">
      <h1>商品信息</h1>
      <el-input
        placeholder="请输入商品名称"
        class="input_sc"
        v-model="input"
        clearable
      >
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="search_goods()"
        >搜索</el-button
      >
      <el-button type="warning" class="last_btn" @click="btn_insert()"
        >+添加商品</el-button
      >
    </div>
    <hr />
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="goodsName" label="商品名称" width="150">
      </el-table-column>
      <el-table-column
        label="图片"
        width="75"
        height="75"
        style="overflow: hidden"
      >
        <template slot-scope="scope">
          <img v-if="scope.row.goodsImg !== null" :src="$api+'/common/download/'+scope.row.goodsImg" style="width: 100%; height: 100%" />
        </template>
      </el-table-column>
      <el-table-column prop="goodsPrice" label="价格"> </el-table-column>
      <el-table-column prop="goodsStatus" label="售卖状态"> </el-table-column>
      <el-table-column prop="goodsEndTime" label="最后操作时间">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="warning"
            class="update_btn"
            @click="btn_update(scope.row)"
            circle
            >修改</el-button
          >
          <el-button
            type="primary"
            class="update_btn"
            @click="slot_btn(1, scope.row)"
            v-if="scope.row.goodsStatus === 1"
            circle
            >停售</el-button
          >
          <el-button
            type="success"
            class="update_btn"
            @click="slot_btn(2, scope.row)"
            v-else
            circle
            >启售</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delete_goods(scope.row.goodsId)"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      @current-change="changePageCurrent"
      :page-size="8"
      :total="page_total"
    >
    </el-pagination>

    <!-- 添加商品、修改商品 -->
    <el-dialog
      :title="do_title"
      :visible.sync="centerDialogVisible"
      width="40%"
      :modal="false"
      center
    >
      <div>
        <ul>
          <li>商品名称</li>
          <li><input type="text" v-model="flower_infor.goodsName" /></li>
          <li>
            <div v-for="(item,index) in imgUrl" :key="index" style="height: 148px; width: 148px;overflow: hidden; float: left; margin-right: 25px;">
              <img :src="$api+'/common/download/'+item" style="width: 100%; height: 100%;">
            </div>
            <el-upload
              v-if="flag == 2 || (count != 4 && flag != 1)"
              :action="$api + '/common/upload'"
              list-type="picture-card"
              :limit="4"
              :on-success="onSuccess"
              :before-upload="beforeAvatarUpload"
              :on-change="onChange"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </li>
          <li>商品价格</li>
          <li><input type="text" v-model="flower_infor.goodsPrice" /></li>
          <li>商品类型</li>
          <li>
            <select v-model="flower_infor.flowerType">
              <option
                v-for="(item, index) in flower_type"
                :key="index"
                :value="index"
              >
                {{ item }}
              </option>
            </select>
            <select v-model="flower_infor.flowerGive">
              <option
                v-for="(item, index) in flower_give"
                :key="index"
                :value="index"
              >
                {{ item }}
              </option>
            </select>
            <select v-model="flower_infor.flowerSpecial">
              <option
                v-for="(item, index) in flower_special"
                :key="index"
                :value="index"
              >
                {{ item }}
              </option>
            </select>
          </li>
          <li>商品材料</li>
          <li><input type="text" v-model="flower_infor.goodsMaterial" /></li>
          <li>商品规格</li>
          <li><input type="text" v-model="flower_infor.goodsSpec" placeholder="不同规格请使用,隔开" /></li>
          <li>商品包装</li>
          <li><input type="text" v-model="flower_infor.goodsPackage" /></li>
          <li>商品说明</li>
          <li><input type="text" v-model="flower_infor.goodsIllustrate" /></li>
          <li>花语</li>
          <li><input type="text" v-model="flower_infor.goodsFlowerLanguage" /></li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qu_xiao()">取 消</el-button>
        <el-button type="primary" @click="btn_definite()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
select {
  margin-right: 5px;
  height: 50px;
  width: 130px;
  font-size: 16px;
}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
li {
  list-style-type: none;
  font-size: 18px;
  margin: 10px 0;
}
input {
  outline: none;
  height: 40px;
  font-size: 16px;
  padding-left: 10px;
  width: 400px;
}
.app {
  .header {
    position: relative;
    padding-bottom: 20px;
    padding-top: 25px;
    h1 {
      position: absolute;
      top: 5px;
      left: 20px;
      font-size: 25px;
    }
    .input_sc {
      width: 300px;
    }
    .last_btn {
      position: absolute;
      top: 25px;
      right: 50px;
    }
  }
  .update_btn {
    font-size: 8px;
  }
}
</style>
